5 * Created on August 16, 2007
7 * Copyright © 2007 Iker Labarga <Firstname><Lastname>@gmail.com
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
28 * A module that allows for editing and creating pages.
30 * Currently, this wraps around the EditPage class in an ugly way,
31 * EditPage.php should be rewritten to provide a cleaner interface
34 class ApiEditPage
extends ApiBase
{
36 public function __construct( $query, $moduleName ) {
37 parent
::__construct( $query, $moduleName );
40 public function execute() {
41 $user = $this->getUser();
42 $params = $this->extractRequestParams();
44 if ( is_null( $params['text'] ) && is_null( $params['appendtext'] ) &&
45 is_null( $params['prependtext'] ) &&
46 $params['undo'] == 0 )
48 $this->dieUsageMsg( 'missingtext' );
51 $titleObj = $this->getTitleOrPageId( $params );
52 if ( $titleObj->isExternal() ) {
53 $this->dieUsageMsg( array( 'invalidtitle', $params['title'] ) );
56 $apiResult = $this->getResult();
58 if ( $params['redirect'] ) {
59 if ( $titleObj->isRedirect() ) {
60 $oldTitle = $titleObj;
62 $titles = Title
::newFromRedirectArray( Revision
::newFromTitle( $oldTitle )->getText( Revision
::FOR_THIS_USER
) );
63 // array_shift( $titles );
65 $redirValues = array();
66 foreach ( $titles as $id => $newTitle ) {
68 if ( !isset( $titles[ $id - 1 ] ) ) {
69 $titles[ $id - 1 ] = $oldTitle;
72 $redirValues[] = array(
73 'from' => $titles[ $id - 1 ]->getPrefixedText(),
74 'to' => $newTitle->getPrefixedText()
77 $titleObj = $newTitle;
80 $apiResult->setIndexedTagName( $redirValues, 'r' );
81 $apiResult->addValue( null, 'redirects', $redirValues );
85 if ( $params['createonly'] && $titleObj->exists() ) {
86 $this->dieUsageMsg( 'createonly-exists' );
88 if ( $params['nocreate'] && !$titleObj->exists() ) {
89 $this->dieUsageMsg( 'nocreate-missing' );
92 // Now let's check whether we're even allowed to do this
93 $errors = $titleObj->getUserPermissionsErrors( 'edit', $user );
94 if ( !$titleObj->exists() ) {
95 $errors = array_merge( $errors, $titleObj->getUserPermissionsErrors( 'create', $user ) );
97 if ( count( $errors ) ) {
98 $this->dieUsageMsg( $errors[0] );
101 $articleObj = Article
::newFromTitle( $titleObj, $this->getContext() );
103 $toMD5 = $params['text'];
104 if ( !is_null( $params['appendtext'] ) ||
!is_null( $params['prependtext'] ) )
106 // For non-existent pages, Article::getContent()
107 // returns an interface message rather than ''
108 // We do want getContent()'s behavior for non-existent
109 // MediaWiki: pages, though
110 if ( $articleObj->getID() == 0 && $titleObj->getNamespace() != NS_MEDIAWIKI
) {
114 $content = $articleObj->getContentObject();
115 $text = ContentHandler
::getContentText( $content ); #FIXME: serialize?! get format from params?...
118 if ( !is_null( $params['section'] ) ) {
119 // Process the content for section edits
120 $section = intval( $params['section'] );
121 $sectionContent = $content->getSection( $section );
122 $text = ContentHandler
::getContentText( $sectionContent ); #FIXME: serialize?! get format from params?...
123 if ( $text === false ||
$text === null ) {
124 $this->dieUsage( "There is no section {$section}.", 'nosuchsection' );
127 $params['text'] = $params['prependtext'] . $text . $params['appendtext'];
128 $toMD5 = $params['prependtext'] . $params['appendtext'];
131 if ( $params['undo'] > 0 ) {
132 if ( $params['undoafter'] > 0 ) {
133 if ( $params['undo'] < $params['undoafter'] ) {
134 list( $params['undo'], $params['undoafter'] ) =
135 array( $params['undoafter'], $params['undo'] );
137 $undoafterRev = Revision
::newFromID( $params['undoafter'] );
139 $undoRev = Revision
::newFromID( $params['undo'] );
140 if ( is_null( $undoRev ) ||
$undoRev->isDeleted( Revision
::DELETED_TEXT
) ) {
141 $this->dieUsageMsg( array( 'nosuchrevid', $params['undo'] ) );
144 if ( $params['undoafter'] == 0 ) {
145 $undoafterRev = $undoRev->getPrevious();
147 if ( is_null( $undoafterRev ) ||
$undoafterRev->isDeleted( Revision
::DELETED_TEXT
) ) {
148 $this->dieUsageMsg( array( 'nosuchrevid', $params['undoafter'] ) );
151 if ( $undoRev->getPage() != $articleObj->getID() ) {
152 $this->dieUsageMsg( array( 'revwrongpage', $undoRev->getID(), $titleObj->getPrefixedText() ) );
154 if ( $undoafterRev->getPage() != $articleObj->getID() ) {
155 $this->dieUsageMsg( array( 'revwrongpage', $undoafterRev->getID(), $titleObj->getPrefixedText() ) );
158 $newtext = $articleObj->getUndoText( $undoRev, $undoafterRev );
159 if ( $newtext === false ) {
160 $this->dieUsageMsg( 'undo-failure' );
162 $params['text'] = $newtext;
163 // If no summary was given and we only undid one rev,
164 // use an autosummary
165 if ( is_null( $params['summary'] ) && $titleObj->getNextRevisionID( $undoafterRev->getID() ) == $params['undo'] ) {
166 $params['summary'] = wfMsgForContent( 'undo-summary', $params['undo'], $undoRev->getUserText() );
170 // See if the MD5 hash checks out
171 if ( !is_null( $params['md5'] ) && md5( $toMD5 ) !== $params['md5'] ) {
172 $this->dieUsageMsg( 'hashcheckfailed' );
175 // EditPage wants to parse its stuff from a WebRequest
176 // That interface kind of sucks, but it's workable
177 $requestArray = array(
178 'wpTextbox1' => $params['text'],
179 'wpEditToken' => $params['token'],
180 'wpIgnoreBlankSummary' => ''
183 if ( !is_null( $params['summary'] ) ) {
184 $requestArray['wpSummary'] = $params['summary'];
187 if ( !is_null( $params['sectiontitle'] ) ) {
188 $requestArray['wpSectionTitle'] = $params['sectiontitle'];
191 // Watch out for basetimestamp == ''
192 // wfTimestamp() treats it as NOW, almost certainly causing an edit conflict
193 if ( !is_null( $params['basetimestamp'] ) && $params['basetimestamp'] != '' ) {
194 $requestArray['wpEdittime'] = wfTimestamp( TS_MW
, $params['basetimestamp'] );
196 $requestArray['wpEdittime'] = $articleObj->getTimestamp();
199 if ( !is_null( $params['starttimestamp'] ) && $params['starttimestamp'] != '' ) {
200 $requestArray['wpStarttime'] = wfTimestamp( TS_MW
, $params['starttimestamp'] );
202 $requestArray['wpStarttime'] = wfTimestampNow(); // Fake wpStartime
205 if ( $params['minor'] ||
( !$params['notminor'] && $user->getOption( 'minordefault' ) ) ) {
206 $requestArray['wpMinoredit'] = '';
209 if ( $params['recreate'] ) {
210 $requestArray['wpRecreate'] = '';
213 if ( !is_null( $params['section'] ) ) {
214 $section = intval( $params['section'] );
215 if ( $section == 0 && $params['section'] != '0' && $params['section'] != 'new' ) {
216 $this->dieUsage( "The section parameter must be set to an integer or 'new'", "invalidsection" );
218 $requestArray['wpSection'] = $params['section'];
220 $requestArray['wpSection'] = '';
223 $watch = $this->getWatchlistValue( $params['watchlist'], $titleObj );
225 // Deprecated parameters
226 if ( $params['watch'] ) {
228 } elseif ( $params['unwatch'] ) {
233 $requestArray['wpWatchthis'] = '';
236 global $wgTitle, $wgRequest;
238 $req = new DerivativeRequest( $this->getRequest(), $requestArray, true );
240 // Some functions depend on $wgTitle == $ep->mTitle
241 // TODO: Make them not or check if they still do
242 $wgTitle = $titleObj;
244 $handler = ContentHandler
::getForTitle( $titleObj );
245 $ep = $handler->createEditPage( $articleObj );
247 $ep->setContextTitle( $titleObj );
248 $ep->importFormData( $req );
251 // Handle APIEditBeforeSave parameters
253 if ( !wfRunHooks( 'APIEditBeforeSave', array( $ep, $ep->textbox1
, &$r ) ) ) {
255 $r['result'] = 'Failure';
256 $apiResult->addValue( null, $this->getModuleName(), $r );
259 $this->dieUsageMsg( 'hookaborted' );
263 // Do the actual save
264 $oldRevId = $articleObj->getRevIdFetched();
266 // Fake $wgRequest for some hooks inside EditPage
267 // @todo FIXME: This interface SUCKS
268 $oldRequest = $wgRequest;
271 $status = $ep->internalAttemptSave( $result, $user->isAllowed( 'bot' ) && $params['bot'] );
272 $wgRequest = $oldRequest;
273 global $wgMaxArticleSize;
275 switch( $status->value
) {
276 case EditPage
::AS_HOOK_ERROR
:
277 case EditPage
::AS_HOOK_ERROR_EXPECTED
:
278 $this->dieUsageMsg( 'hookaborted' );
280 case EditPage
::AS_IMAGE_REDIRECT_ANON
:
281 $this->dieUsageMsg( 'noimageredirect-anon' );
283 case EditPage
::AS_IMAGE_REDIRECT_LOGGED
:
284 $this->dieUsageMsg( 'noimageredirect-logged' );
286 case EditPage
::AS_SPAM_ERROR
:
287 $this->dieUsageMsg( array( 'spamdetected', $result['spam'] ) );
289 case EditPage
::AS_BLOCKED_PAGE_FOR_USER
:
290 $this->dieUsageMsg( 'blockedtext' );
292 case EditPage
::AS_MAX_ARTICLE_SIZE_EXCEEDED
:
293 case EditPage
::AS_CONTENT_TOO_BIG
:
294 $this->dieUsageMsg( array( 'contenttoobig', $wgMaxArticleSize ) );
296 case EditPage
::AS_READ_ONLY_PAGE_ANON
:
297 $this->dieUsageMsg( 'noedit-anon' );
299 case EditPage
::AS_READ_ONLY_PAGE_LOGGED
:
300 $this->dieUsageMsg( 'noedit' );
302 case EditPage
::AS_READ_ONLY_PAGE
:
303 $this->dieReadOnly();
305 case EditPage
::AS_RATE_LIMITED
:
306 $this->dieUsageMsg( 'actionthrottledtext' );
308 case EditPage
::AS_ARTICLE_WAS_DELETED
:
309 $this->dieUsageMsg( 'wasdeleted' );
311 case EditPage
::AS_NO_CREATE_PERMISSION
:
312 $this->dieUsageMsg( 'nocreate-loggedin' );
314 case EditPage
::AS_BLANK_ARTICLE
:
315 $this->dieUsageMsg( 'blankpage' );
317 case EditPage
::AS_CONFLICT_DETECTED
:
318 $this->dieUsageMsg( 'editconflict' );
320 // case EditPage::AS_SUMMARY_NEEDED: Can't happen since we set wpIgnoreBlankSummary
321 case EditPage
::AS_TEXTBOX_EMPTY
:
322 $this->dieUsageMsg( 'emptynewsection' );
324 case EditPage
::AS_SUCCESS_NEW_ARTICLE
:
327 case EditPage
::AS_SUCCESS_UPDATE
:
328 $r['result'] = 'Success';
329 $r['pageid'] = intval( $titleObj->getArticleID() );
330 $r['title'] = $titleObj->getPrefixedText();
331 $newRevId = $articleObj->getLatest();
332 if ( $newRevId == $oldRevId ) {
335 $r['oldrevid'] = intval( $oldRevId );
336 $r['newrevid'] = intval( $newRevId );
337 $r['newtimestamp'] = wfTimestamp( TS_ISO_8601
,
338 $articleObj->getTimestamp() );
342 case EditPage
::AS_SUMMARY_NEEDED
:
343 $this->dieUsageMsg( 'summaryrequired' );
345 case EditPage
::AS_END
:
346 // $status came from WikiPage::doEdit()
347 $errors = $status->getErrorsArray();
348 $this->dieUsageMsg( $errors[0] ); // TODO: Add new errors to message map
351 if ( is_string( $status->value
) && strlen( $status->value
) ) {
352 $this->dieUsage( "An unknown return value was returned by Editpage. The code returned was \"{$status->value}\"" , $status->value
);
354 $this->dieUsageMsg( array( 'unknownerror', $status->value
) );
357 $apiResult->addValue( null, $this->getModuleName(), $r );
360 public function mustBePosted() {
364 public function isWriteMode() {
368 public function getDescription() {
369 return 'Create and edit pages.';
372 public function getPossibleErrors() {
373 global $wgMaxArticleSize;
375 return array_merge( parent
::getPossibleErrors(),
376 $this->getTitleOrPageIdErrorMessage(),
378 array( 'nosuchpageid', 'pageid' ),
379 array( 'missingtext' ),
380 array( 'invalidtitle', 'title' ),
381 array( 'createonly-exists' ),
382 array( 'nocreate-missing' ),
383 array( 'nosuchrevid', 'undo' ),
384 array( 'nosuchrevid', 'undoafter' ),
385 array( 'revwrongpage', 'id', 'text' ),
386 array( 'undo-failure' ),
387 array( 'hashcheckfailed' ),
388 array( 'hookaborted' ),
389 array( 'noimageredirect-anon' ),
390 array( 'noimageredirect-logged' ),
391 array( 'spamdetected', 'spam' ),
392 array( 'summaryrequired' ),
393 array( 'blockedtext' ),
394 array( 'contenttoobig', $wgMaxArticleSize ),
395 array( 'noedit-anon' ),
397 array( 'actionthrottledtext' ),
398 array( 'wasdeleted' ),
399 array( 'nocreate-loggedin' ),
400 array( 'blankpage' ),
401 array( 'editconflict' ),
402 array( 'emptynewsection' ),
403 array( 'unknownerror', 'retval' ),
404 array( 'code' => 'nosuchsection', 'info' => 'There is no section section.' ),
405 array( 'code' => 'invalidsection', 'info' => 'The section parameter must be set to an integer or \'new\'' ),
406 array( 'customcssprotected' ),
407 array( 'customjsprotected' ),
412 public function getAllowedParams() {
415 ApiBase
::PARAM_TYPE
=> 'string',
418 ApiBase
::PARAM_TYPE
=> 'integer',
421 'sectiontitle' => array(
422 ApiBase
::PARAM_TYPE
=> 'string',
423 ApiBase
::PARAM_REQUIRED
=> false,
431 'basetimestamp' => null,
432 'starttimestamp' => null,
434 'createonly' => false,
437 ApiBase
::PARAM_DFLT
=> false,
438 ApiBase
::PARAM_DEPRECATED
=> true,
441 ApiBase
::PARAM_DFLT
=> false,
442 ApiBase
::PARAM_DEPRECATED
=> true,
444 'watchlist' => array(
445 ApiBase
::PARAM_DFLT
=> 'preferences',
446 ApiBase
::PARAM_TYPE
=> array(
454 'prependtext' => null,
455 'appendtext' => null,
457 ApiBase
::PARAM_TYPE
=> 'integer'
459 'undoafter' => array(
460 ApiBase
::PARAM_TYPE
=> 'integer'
463 ApiBase
::PARAM_TYPE
=> 'boolean',
464 ApiBase
::PARAM_DFLT
=> false,
469 public function getParamDescription() {
470 $p = $this->getModulePrefix();
472 'title' => "Title of the page you want to edit. Cannot be used together with {$p}pageid",
473 'pageid' => "Page ID of the page you want to edit. Cannot be used together with {$p}title",
474 'section' => 'Section number. 0 for the top section, \'new\' for a new section',
475 'sectiontitle' => 'The title for a new section',
476 'text' => 'Page content',
477 'token' => array( 'Edit token. You can get one of these through prop=info.',
478 "The token should always be sent as the last parameter, or at least, after the {$p}text parameter"
480 'summary' => "Edit summary. Also section title when {$p}section=new and {$p}sectiontitle is not set",
481 'minor' => 'Minor edit',
482 'notminor' => 'Non-minor edit',
483 'bot' => 'Mark this edit as bot',
484 'basetimestamp' => array( 'Timestamp of the base revision (obtained through prop=revisions&rvprop=timestamp).',
485 'Used to detect edit conflicts; leave unset to ignore conflicts'
487 'starttimestamp' => array( 'Timestamp when you obtained the edit token.',
488 'Used to detect edit conflicts; leave unset to ignore conflicts'
490 'recreate' => 'Override any errors about the article having been deleted in the meantime',
491 'createonly' => 'Don\'t edit the page if it exists already',
492 'nocreate' => 'Throw an error if the page doesn\'t exist',
493 'watch' => 'Add the page to your watchlist',
494 'unwatch' => 'Remove the page from your watchlist',
495 'watchlist' => 'Unconditionally add or remove the page from your watchlist, use preferences or do not change watch',
496 'md5' => array( "The MD5 hash of the {$p}text parameter, or the {$p}prependtext and {$p}appendtext parameters concatenated.",
497 'If set, the edit won\'t be done unless the hash is correct' ),
498 'prependtext' => "Add this text to the beginning of the page. Overrides {$p}text",
499 'appendtext' => array( "Add this text to the end of the page. Overrides {$p}text.",
500 "Use {$p}section=new to append a new section" ),
501 'undo' => "Undo this revision. Overrides {$p}text, {$p}prependtext and {$p}appendtext",
502 'undoafter' => 'Undo all revisions from undo to this one. If not set, just undo one revision',
503 'redirect' => 'Automatically resolve redirects',
507 public function needsToken() {
511 public function getTokenSalt() {
515 public function getExamples() {
518 'api.php?action=edit&title=Test&summary=test%20summary&text=article%20content&basetimestamp=20070824123454&token=%2B\\'
519 => 'Edit a page (anonymous user)',
521 'api.php?action=edit&title=Test&summary=NOTOC&minor=&prependtext=__NOTOC__%0A&basetimestamp=20070824123454&token=%2B\\'
522 => 'Prepend __NOTOC__ to a page (anonymous user)',
523 'api.php?action=edit&title=Test&undo=13585&undoafter=13579&basetimestamp=20070824123454&token=%2B\\'
524 => 'Undo r13579 through r13585 with autosummary (anonymous user)',
528 public function getHelpUrls() {
529 return 'https://www.mediawiki.org/wiki/API:Edit';
532 public function getVersion() {
533 return __CLASS__
. ': $Id$';